package com.xy.wsl.api.controller.Util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
@RequestMapping("/video")
@Slf4j
@RestController
public class videoController {

    @GetMapping("download")
    public ResponseEntity<byte[]> downloadVideo(String videoUrl) {
        try {
            videoUrl = videoUrl.replace("download/?videoUrl=","");
            URL url = new URL( URLDecoder.decode(videoUrl, "UTF-8"));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            InputStream inputStream = connection.getInputStream();

            byte[] videoBytes = inputStream.readAllBytes();

            HttpHeaders headers = new HttpHeaders();
//            MediaType.APPLICATION_OCTET_STREAM
            headers.setContentType(MediaType.parseMediaType("video/mp4"));
            headers.setContentDispositionFormData("attachment", "video.mp4");

            return new ResponseEntity<>(videoBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
